﻿using System.ComponentModel.Composition;
using System.Threading.Tasks;
using NthDownload.Contracts;
using NthDownload.DownloadPlugins.Http.Serialization;

namespace NthDownload.DownloadPlugins.Http.Persistence
{
    [PartCreationPolicy(CreationPolicy.Shared)]
    [Export]
    public class HttpSettingsPersistenceService
    {
        #region Methods

        /// <summary>
        /// Loads profile data
        /// </summary>
        public Task Load()
        {
            Task task = new Task(() =>
            {
                Task<string> loadTask = PersistenceService.Load("HttpSettings");
                loadTask.Wait();

                if (loadTask.Result != null)
                {
                    HttpSettingsXmlSerializationService HttpSettingsXmlSerializationService = new HttpSettingsXmlSerializationService();
                    HttpSettingsXmlSerializationService.Deserialize(loadTask.Result, Settings);
                }
            });

            task.Start();
            return task;
        }

        /// <summary>
        /// Saves profile data
        /// </summary>
        public Task Save()
        {
            Task task = new Task(() =>
            {
                HttpSettingsXmlSerializationService HttpSettingsXmlSerializationService = new HttpSettingsXmlSerializationService();
                string data = HttpSettingsXmlSerializationService.Serialize(Settings);

                Task saveTask = PersistenceService.Save("HttpSettings", data);
                saveTask.Wait();
            });

            task.Start();
            return task;
        }

        #endregion Methods

        #region Properties

        /// <summary>
        /// The profile persistence service
        /// </summary>
        [Import(AllowRecomposition = true)]
        public IKeyValuePairPersistenceService PersistenceService { get; set; }

        /// <summary>
        /// Settings
        /// </summary>
        [Import(AllowRecomposition = true)]
        public HttpSettings Settings { get; set; }

        #endregion Properties
    }
}
